#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速安装脚本
Quick Installation Script for AI Content Reliability Detection System
"""

import os
import sys
import subprocess
import platform

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"Python版本检查通过: {sys.version}")
    return True

def install_dependencies():
    """安装依赖包"""
    print("正在安装依赖包...")
    
    # 基础依赖
    basic_deps = [
        'flask>=2.3.3',
        'requests>=2.31.0',
        'python-dotenv>=1.0.0'
    ]
    
    # 可选依赖
    optional_deps = [
        'numpy>=1.24.3',
        'pandas>=2.0.3',
        'jieba>=0.42.1',
        'sentence-transformers>=2.2.2',
        'scikit-learn>=1.3.0'
    ]
    
    # 文档处理依赖
    document_deps = [
        'PyPDF2>=3.0.1',
        'python-docx>=0.8.11',
        'openpyxl>=3.1.2',
        'beautifulsoup4>=4.12.2',
        'lxml>=4.9.3'
    ]
    
    try:
        # 安装基础依赖
        print("安装基础依赖...")
        for dep in basic_deps:
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', dep])
        
        # 询问是否安装可选依赖
        print("\n可选依赖包:")
        for i, dep in enumerate(optional_deps, 1):
            print(f"{i}. {dep}")
        
        choice = input("\n是否安装可选依赖? (y/n): ").lower().strip()
        if choice in ['y', 'yes', '是']:
            print("安装可选依赖...")
            for dep in optional_deps:
                try:
                    subprocess.check_call([sys.executable, '-m', 'pip', 'install', dep])
                except subprocess.CalledProcessError:
                    print(f"警告: 安装 {dep} 失败，跳过")
        
        # 询问是否安装文档处理依赖
        print("\n文档处理依赖包:")
        for i, dep in enumerate(document_deps, 1):
            print(f"{i}. {dep}")
        
        choice = input("\n是否安装文档处理依赖? (y/n): ").lower().strip()
        if choice in ['y', 'yes', '是']:
            print("安装文档处理依赖...")
            for dep in document_deps:
                try:
                    subprocess.check_call([sys.executable, '-m', 'pip', 'install', dep])
                except subprocess.CalledProcessError:
                    print(f"警告: 安装 {dep} 失败，跳过")
        
        print("依赖安装完成！")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"安装依赖失败: {e}")
        return False

def create_directories():
    """创建必要的目录"""
    print("创建必要的目录...")
    
    directories = [
        'knowledge_base',
        'logs',
        'templates',
        'static'
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        print(f"创建目录: {directory}")

def create_templates():
    """创建HTML模板文件"""
    print("创建HTML模板文件...")
    
    templates_dir = 'templates'
    os.makedirs(templates_dir, exist_ok=True)
    
    # 创建index.html
    index_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI内容可靠性检测系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .result-card {
            margin-top: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .progress {
            height: 25px;
        }
        .removed-section {
            background-color: #ffe6e6;
            padding: 5px;
            margin: 2px 0;
            border-radius: 3px;
            border-left: 3px solid #dc3545;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-5">AI内容可靠性检测系统</h1>
        
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h5>内容检测</h5>
                    </div>
                    <div class="card-body">
                        <form id="detectForm">
                            <div class="mb-3">
                                <label for="content" class="form-label">待检测内容</label>
                                <textarea class="form-control" id="content" rows="6" 
                                    placeholder="请输入要检测的内容..."></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="sources" class="form-label">信息来源（可选，每行一个）</label>
                                <textarea class="form-control" id="sources" rows="3" 
                                    placeholder="https://example.com/article1&#10;https://arxiv.org/abs/2023.12345"></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">开始检测</button>
                        </form>
                    </div>
                </div>
                
                <div id="resultCard" class="card result-card" style="display: none;">
                    <div class="card-header">
                        <h5>检测结果</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>AI生成概率</h6>
                                <div class="progress mb-3">
                                    <div id="aiProgress" class="progress-bar" role="progressbar"></div>
                                </div>
                                <p id="aiProbability" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <h6>可靠性评分</h6>
                                <div class="progress mb-3">
                                    <div id="reliabilityProgress" class="progress-bar" role="progressbar"></div>
                                </div>
                                <p id="reliabilityScore" class="text-muted"></p>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6>内容类型</h6>
                                <span id="contentType" class="badge bg-info"></span>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6>过滤后的内容</h6>
                                <div id="filteredContent" class="border p-3 bg-light rounded"></div>
                            </div>
                        </div>
                        
                        <div id="removedSections" class="row mt-3" style="display: none;">
                            <div class="col-12">
                                <h6>移除的部分</h6>
                                <div id="removedList"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('detectForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const content = document.getElementById('content').value;
            const sourcesText = document.getElementById('sources').value;
            const sources = sourcesText.split('\\n').filter(s => s.trim());
            
            if (!content.trim()) {
                alert('请输入要检测的内容');
                return;
            }
            
            // 显示加载状态
            const submitBtn = document.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.textContent = '检测中...';
            
            try {
                const response = await fetch('/api/detect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: content,
                        sources: sources
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    displayResult(result);
                } else {
                    alert('检测失败: ' + result.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '开始检测';
            }
        });
        
        function displayResult(result) {
            // 显示结果卡片
            document.getElementById('resultCard').style.display = 'block';
            
            // 更新AI概率
            const aiProgress = document.getElementById('aiProgress');
            const aiProbability = document.getElementById('aiProbability');
            const aiPercent = Math.round(result.ai_probability * 100);
            aiProgress.style.width = aiPercent + '%';
            aiProgress.textContent = aiPercent + '%';
            aiProbability.textContent = `AI生成概率: ${result.ai_probability.toFixed(2)}`;
            
            // 设置进度条颜色
            if (aiPercent > 80) {
                aiProgress.className = 'progress-bar bg-danger';
            } else if (aiPercent > 50) {
                aiProgress.className = 'progress-bar bg-warning';
            } else {
                aiProgress.className = 'progress-bar bg-success';
            }
            
            // 更新可靠性评分
            const reliabilityProgress = document.getElementById('reliabilityProgress');
            const reliabilityScore = document.getElementById('reliabilityScore');
            const reliabilityPercent = Math.round(result.reliability_score * 100);
            reliabilityProgress.style.width = reliabilityPercent + '%';
            reliabilityProgress.textContent = reliabilityPercent + '%';
            reliabilityScore.textContent = `可靠性评分: ${result.reliability_score.toFixed(2)}`;
            
            // 设置可靠性进度条颜色
            if (reliabilityPercent > 70) {
                reliabilityProgress.className = 'progress-bar bg-success';
            } else if (reliabilityPercent > 40) {
                reliabilityProgress.className = 'progress-bar bg-warning';
            } else {
                reliabilityProgress.className = 'progress-bar bg-danger';
            }
            
            // 更新内容类型
            const contentType = document.getElementById('contentType');
            contentType.textContent = result.content_type;
            
            // 更新过滤后的内容
            document.getElementById('filteredContent').textContent = result.filtered_content;
            
            // 更新移除的部分
            const removedSections = document.getElementById('removedSections');
            const removedList = document.getElementById('removedList');
            
            if (result.removed_sections && result.removed_sections.length > 0) {
                removedSections.style.display = 'block';
                removedList.innerHTML = '';
                result.removed_sections.forEach(section => {
                    const div = document.createElement('div');
                    div.className = 'removed-section';
                    div.textContent = section;
                    removedList.appendChild(div);
                });
            } else {
                removedSections.style.display = 'none';
            }
        }
    </script>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'index.html'), 'w', encoding='utf-8') as f:
        f.write(index_html)
    print("创建模板: templates/index.html")
    
    # 创建demo.html
    demo_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统演示 - AI内容可靠性检测</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-5">系统演示</h1>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>知识库管理</h5>
                    </div>
                    <div class="card-body">
                        <form id="knowledgeForm">
                            <div class="mb-3">
                                <label for="title" class="form-label">标题</label>
                                <input type="text" class="form-control" id="title" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="kbContent" class="form-label">内容</label>
                                <textarea class="form-control" id="kbContent" rows="4" required></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="source" class="form-label">来源</label>
                                <input type="url" class="form-control" id="source" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="sourceType" class="form-label">类型</label>
                                <select class="form-control" id="sourceType">
                                    <option value="academic">学术论文</option>
                                    <option value="government">政府文件</option>
                                    <option value="news">新闻文章</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="reliability" class="form-label">可靠性评分 (0-1)</label>
                                <input type="number" class="form-control" id="reliability" 
                                       min="0" max="1" step="0.1" value="0.8">
                            </div>
                            
                            <button type="submit" class="btn btn-success">添加到知识库</button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>信息验证</h5>
                    </div>
                    <div class="card-body">
                        <form id="verifyForm">
                            <div class="mb-3">
                                <label for="claim" class="form-label">待验证声明</label>
                                <textarea class="form-control" id="claim" rows="3" 
                                    placeholder="请输入要验证的声明..."></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-info">验证信息</button>
                        </form>
                        
                        <div id="verifyResult" class="mt-3" style="display: none;">
                            <h6>验证结果</h6>
                            <div id="verifyContent" class="border p-3 bg-light rounded"></div>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-3">
                    <div class="card-header">
                        <h5>知识库统计</h5>
                    </div>
                    <div class="card-body">
                        <button id="getStats" class="btn btn-secondary">获取统计信息</button>
                        <div id="statsResult" class="mt-3" style="display: none;">
                            <div id="statsContent" class="border p-3 bg-light rounded"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 知识库表单处理
        document.getElementById('knowledgeForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const data = {
                title: document.getElementById('title').value,
                content: document.getElementById('kbContent').value,
                source: document.getElementById('source').value,
                source_type: document.getElementById('sourceType').value,
                reliability_score: parseFloat(document.getElementById('reliability').value)
            };
            
            try {
                const response = await fetch('/api/knowledge/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (response.ok && result.success) {
                    alert('成功添加到知识库！');
                    this.reset();
                } else {
                    alert('添加失败: ' + (result.error || result.message));
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        });
        
        // 验证表单处理
        document.getElementById('verifyForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const claim = document.getElementById('claim').value;
            
            if (!claim.trim()) {
                alert('请输入要验证的声明');
                return;
            }
            
            try {
                const response = await fetch('/api/verify', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ claim: claim })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    document.getElementById('verifyResult').style.display = 'block';
                    document.getElementById('verifyContent').textContent = JSON.stringify(result, null, 2);
                } else {
                    alert('验证失败: ' + result.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        });
        
        // 统计信息处理
        document.getElementById('getStats').addEventListener('click', async function() {
            try {
                const response = await fetch('/api/knowledge/stats');
                const result = await response.json();
                
                if (response.ok) {
                    document.getElementById('statsResult').style.display = 'block';
                    document.getElementById('statsContent').textContent = JSON.stringify(result, null, 2);
                } else {
                    alert('获取统计信息失败: ' + result.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        });
    </script>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'demo.html'), 'w', encoding='utf-8') as f:
        f.write(demo_html)
    print("创建模板: templates/demo.html")

def create_env_file():
    """创建环境变量文件"""
    print("创建环境变量配置文件...")
    
    env_content = """# AI内容可靠性检测系统环境变量配置
# AI Content Reliability Detection System Environment Variables

# API密钥配置（可选）
# API Key Configuration (Optional)
ZEROGPT_API_KEY=your_zerogpt_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
COHERE_API_KEY=your_cohere_api_key_here

# 系统配置
# System Configuration
DEBUG=False
LOG_LEVEL=INFO
"""
    
    with open('.env', 'w', encoding='utf-8') as f:
        f.write(env_content)
    
    print("创建配置文件: .env")
    print("请根据需要修改API密钥配置")

def run_tests():
    """运行系统测试"""
    print("运行系统测试...")
    
    try:
        result = subprocess.run([sys.executable, 'test_system.py'], 
                              capture_output=True, text=True)
        
        if result.returncode == 0:
            print("系统测试通过！")
            return True
        else:
            print("系统测试失败:")
            print(result.stderr)
            return False
            
    except Exception as e:
        print(f"运行测试失败: {e}")
        return False

def show_usage():
    """显示使用说明"""
    print("\n" + "="*50)
    print("安装完成！")
    print("="*50)
    print("\n使用方法:")
    print("1. 启动Web界面:")
    print("   python run.py --mode web")
    print("   或")
    print("   python run.py")
    print("\n2. 命令行模式:")
    print("   python run.py --mode cli")
    print("\n3. 运行测试:")
    print("   python run.py --mode test")
    print("\n4. 直接运行主程序:")
    print("   python ai_content_detector.py")
    print("\n5. 启动Web服务器:")
    print("   python web_interface.py")
    print("\nWeb界面访问地址:")
    print("   http://localhost:5000")
    print("   演示页面: http://localhost:5000/demo")
    print("\n配置文件:")
    print("   环境变量: .env")
    print("   系统配置: config.py")
    print("\n日志文件:")
    print("   ai_detector.log")
    print("\n知识库文件:")
    print("   knowledge_base.db")

def main():
    """主安装函数"""
    print("=== AI内容可靠性检测系统 - 快速安装 ===")
    print(f"操作系统: {platform.system()} {platform.release()}")
    print(f"Python版本: {sys.version}")
    
    # 检查Python版本
    if not check_python_version():
        return 1
    
    # 创建目录
    create_directories()
    
    # 创建模板文件
    create_templates()
    
    # 安装依赖
    try:
        if not install_dependencies():
            print("安装依赖失败，但将继续创建模板文件")
    except Exception as e:
        print(f"安装依赖时出错: {e}")
        print("将继续创建模板文件")
    
    # 创建环境变量文件
    create_env_file()
    
    # 运行测试
    if not run_tests():
        print("系统测试失败，但安装已完成")
        print("请检查错误信息并手动测试")
    
    # 显示使用说明
    show_usage()
    
    print("\n安装完成！系统已准备就绪。")
    return 0

if __name__ == "__main__":
    sys.exit(main()) 